package collection;

import org.junit.Test;

import java.util.*;

/**
 * Created by :Infaraway
 * DATE : 2017/3/26
 * Time : 16:39
 * Funtion :
 */
public class CollectionsTest {

    @Test
    public void testList(){
        List list = new ArrayList<>();
        list.add(new Person("AAA",16));
        list.add(new Person("BBB",13));
        list.add(new Person("CCC",11));
        list.add(new Person("DDD",15));

        for (Object o : list) {
            System.out.println(o.toString());
        }
        //按年龄升序排列
        //实现Comparator类进行排序操作
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Person && o2 instanceof Person){
                    Person p1 = (Person)o1;
                    Person p2 = (Person)o2;
                    return p1.getAge() - p2.getAge();
                }
                throw new ClassCastException("类型转换异常");
            }
        });

        System.out.println();
        for (Object o : list) {
            System.out.println(o.toString());
        }


        //获取list中最小的元素
        //要求集合中的元素都实现Compareable接口
        Set set = new HashSet();

        set.add(new PersonCompare("AAA",20));
        set.add(new PersonCompare("BBB",34));
        set.add(new PersonCompare("CCC",27));
        set.add(new PersonCompare("DDD",29));

        for (Object person : set) {
            System.out.println(person.toString());
        }
        System.out.println();

        Object object = Collections.min(set);
        System.out.println(object.toString());
    }

}
